package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.TimeReport;
import com.example.chamberlainserver.Service.TimeReportService;
import com.example.chamberlainserver.Vo.Request.TimeReport.TimeReportQuery;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 时间填报控制器
 */
@Slf4j
@RestController
@RequestMapping("/timeReport")
public class TimeReportController {
    
    @Autowired
    private TimeReportService timeReportService;
    
    /**
     * 添加时间填报记录
     */
    @PostMapping("/add")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Boolean> addTimeReport(@RequestBody TimeReport timeReport) {
        log.info("添加时间填报记录请求: {}", timeReport);
        try {
            boolean result = timeReportService.addTimeReport(timeReport);
            if (result) {
                return ApiResponse.success("添加时间填报记录成功", true);
            } else {
                return ApiResponse.error(400, "添加时间填报记录失败，可能该日期已有填报记录");
            }
        } catch (Exception e) {
            log.error("添加时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 根据ID查询时间填报记录
     */
    @GetMapping("/get/{id}")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<TimeReport> getTimeReportById(@PathVariable Integer id) {
        log.info("查询时间填报记录请求: id={}", id);
        try {
            TimeReport timeReport = timeReportService.getTimeReportById(id);
            if (timeReport != null) {
                return ApiResponse.success("查询成功", timeReport);
            } else {
                return ApiResponse.error(404, "未找到该时间填报记录");
            }
        } catch (Exception e) {
            log.error("查询时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 根据用户ID查询时间填报记录列表
     */
    @GetMapping("/user/{userId}")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<List<TimeReport>> getTimeReportsByUserId(@PathVariable Integer userId) {
        log.info("查询用户时间填报记录请求: userId={}", userId);
        try {
            List<TimeReport> timeReports = timeReportService.getTimeReportsByUserId(userId);
            return ApiResponse.success("查询成功", timeReports);
        } catch (Exception e) {
            log.error("查询用户时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 根据用户ID和日期查询时间填报记录
     */
    @GetMapping("/user/{userId}/date/{reportDate}")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<TimeReport> getTimeReportByUserIdAndDate(
            @PathVariable Integer userId,
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate reportDate) {
        log.info("查询用户指定日期时间填报记录请求: userId={}, date={}", userId, reportDate);
        try {
            TimeReport timeReport = timeReportService.getTimeReportByUserIdAndDate(userId, reportDate);
            if (timeReport != null) {
                return ApiResponse.success("查询成功", timeReport);
            } else {
                return ApiResponse.error(404, "未找到该日期的时间填报记录");
            }
        } catch (Exception e) {
            log.error("查询用户指定日期时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 查询所有时间填报记录
     */
    @GetMapping("/all")
    @PreAuthorize("hasAnyRole('COUNSELOR', 'ADMIN')")
    public ApiResponse<List<TimeReport>> getAllTimeReports() {
        log.info("查询所有时间填报记录请求");
        try {
            List<TimeReport> timeReports = timeReportService.getAllTimeReports();
            return ApiResponse.success("查询成功", timeReports);
        } catch (Exception e) {
            log.error("查询所有时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 根据状态查询时间填报记录
     */
    @GetMapping("/status/{status}")
    @PreAuthorize("hasAnyRole('COUNSELOR', 'ADMIN')")
    public ApiResponse<List<TimeReport>> getTimeReportsByStatus(@PathVariable Integer status) {
        log.info("根据状态查询时间填报记录请求: status={}", status);
        try {
            List<TimeReport> timeReports = timeReportService.getTimeReportsByStatus(status);
            return ApiResponse.success("查询成功", timeReports);
        } catch (Exception e) {
            log.error("根据状态查询时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 更新时间填报记录
     */
    @PutMapping("/update")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Boolean> updateTimeReport(@RequestBody TimeReport timeReport) {
        log.info("更新时间填报记录请求: {}", timeReport);
        try {
            boolean result = timeReportService.updateTimeReport(timeReport);
            if (result) {
                return ApiResponse.success("更新时间填报记录成功", true);
            } else {
                return ApiResponse.error(400, "更新时间填报记录失败");
            }
        } catch (Exception e) {
            log.error("更新时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 删除时间填报记录
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Boolean> deleteTimeReport(@PathVariable Integer id) {
        log.info("删除时间填报记录请求: id={}", id);
        try {
            boolean result = timeReportService.deleteTimeReport(id);
            if (result) {
                return ApiResponse.success("删除时间填报记录成功", true);
            } else {
                return ApiResponse.error(400, "删除时间填报记录失败");
            }
        } catch (Exception e) {
            log.error("删除时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 分页查询时间填报记录列表
     */
    @PostMapping("/page")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<PageResult<TimeReport>> getPagedTimeReportList(@RequestBody TimeReportQuery timeReportQuery) {
        log.info("分页查询时间填报记录请求: {}", timeReportQuery);
        try {
            PageResult<TimeReport> pageResult = timeReportService.getPagedTimeReportList(timeReportQuery);
            return ApiResponse.success("查询成功", pageResult);
        } catch (Exception e) {
            log.error("分页查询时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 审核时间填报记录
     */
    @PostMapping("/review/{id}")
    @PreAuthorize("hasAnyRole('COUNSELOR', 'ADMIN')")
    public ApiResponse<Boolean> reviewTimeReport(
            @PathVariable Integer id,
            @RequestParam Integer status,
            @RequestParam Integer reviewerId,
            @RequestParam(required = false) String reviewComment) {
        log.info("审核时间填报记录请求: id={}, status={}, reviewerId={}", id, status, reviewerId);
        try {
            boolean result = timeReportService.reviewTimeReport(id, status, reviewerId, reviewComment);
            if (result) {
                return ApiResponse.success("审核时间填报记录成功", true);
            } else {
                return ApiResponse.error(400, "审核时间填报记录失败");
            }
        } catch (Exception e) {
            log.error("审核时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 批量审核时间填报记录
     */
    @PostMapping("/batchReview")
    @PreAuthorize("hasAnyRole('COUNSELOR', 'ADMIN')")
    public ApiResponse<Boolean> batchReviewTimeReports(
            @RequestParam List<Integer> ids,
            @RequestParam Integer status,
            @RequestParam Integer reviewerId,
            @RequestParam(required = false) String reviewComment) {
        log.info("批量审核时间填报记录请求: ids={}, status={}, reviewerId={}", ids, status, reviewerId);
        try {
            boolean result = timeReportService.batchReviewTimeReports(ids, status, reviewerId, reviewComment);
            if (result) {
                return ApiResponse.success("批量审核时间填报记录成功", true);
            } else {
                return ApiResponse.error(400, "批量审核时间填报记录失败");
            }
        } catch (Exception e) {
            log.error("批量审核时间填报记录异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
    
    /**
     * 获取用户在指定日期范围内的工作时长统计
     */
    @GetMapping("/statistics/{userId}")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Double> getTotalWorkHours(
            @PathVariable Integer userId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        log.info("统计用户工作时长请求: userId={}, startDate={}, endDate={}", userId, startDate, endDate);
        try {
            Double totalHours = timeReportService.getTotalWorkHours(userId, startDate, endDate);
            return ApiResponse.success("统计成功", totalHours);
        } catch (Exception e) {
            log.error("统计用户工作时长异常", e);
            return ApiResponse.error(500, "服务器内部错误");
        }
    }
}